<template>
    <div class="p-makeCompoentSQL">
        <Spin v-if="loading" fix size="large"></Spin>
        <div class="p-makeCompoentSQL-menu">
            <Tabs v-model="tabName" @on-click="onTabChange" :animated="false">
                <TabPane label="组件配置" name="com">
                    <Tree :data="comList" show-checkbox multiple @on-check-change="onCheckChange" filterable check-strictly check-directly></Tree>
                </TabPane>
                <TabPane label="模型" name="model">
                    <Form :lableWidth="100">
                        <FormItem v-for="key in Object.keys(selectedModel)" :key="key" :label="modelObj[key]">
                            <Select filterable multiple transfer transfer-class-name="heightAuto"
                                v-model="selectedModel[key]">
                                <Option v-for="(option, index) in modelListAll[key]" :value="option.value" :key="index">{{option.label}}</Option>
                            </Select>
                        </FormItem>
                    </Form>
                </TabPane>
                <!-- <div class="ivu-p-8">
                    <Input v-if="comList.length || query !== ''" v-model="query" search placeholder="输入菜单名称搜索"
                        @on-change="onComSearch" />
                </div>
                <Tree :data="modelListAll" show-checkbox multiple @on-check-change="onCheckChange" check-strictly check-directly></Tree> -->
            </Tabs>
        </div>
        <div class="p-makeCompoentSQL-content">
            <div class="tool ivu-mb">
                <Checkbox v-model="isNew" class="ivu-mr">是否新增记录</Checkbox>
                <Button type="primary" @click="start">生成SQL</Button>
                <!-- <Button class="ivu-mr" @click="reset">清空</Button> -->
            </div>
            <template v-if="tabName === 'com'">
                <p class="label">已选择：</p>
                <ul class="selected flex">
                    <template v-for="(item,index) in selectedCom">
                        <li v-if="!item.children" :key="index">{{item.label}}</li>
                    </template>
                </ul>
            </template>
            <Input :value="sqlText" disabled type="textarea" :autosize="{minRows: 8, maxRows: 20}" placeholder="sql 语句"/>
        </div>
    </div>
</template>

<script>
import {mapActions, mapState} from "vuex";

const modelObj = {
    consume: '实体-消费模型',
    resource: '实体-资源模型',
    logic: '逻辑模型',
    staticLogic: '静态逻辑',
    twins: '孪生模型',
}
const containerModel = ['logic', 'staticLogic', 'twins']

export default {
    data() {
        return {
            sqlText: '',
            query: '',
            isNew: false,
            loading: false,
            tabName: 'com',
            selectedCom: [],
            selectedModel: {
                consume: [],
                resource: [],
                logic: [],
                staticLogic: [],
                twins: []
            },
            modelObj,
            comListAll: [],
            comList: [],
            modelListAll: {
                consume: [],
                resource: [],
                logic: [],
                staticLogic: [],
                twins: []
            },
        }
    },
    created() {
        this.loadAllModules()
    },
    methods: {
        onTabChange(name) {
            this.sqlText = ''
            this.tabName = name
        },
        onCheckChange(selectedCom, item) {
            this.selectedCom = selectedCom
        },
        reset() {
            this.sqlText = ''
        },
        start() {
            if (this.tabName === 'model') {
                this.startModel()
            }
            if (this.tabName === 'com') {
                this.startCom()
            }
        },
        async startCom() {
            let sqlText = `${this.isNew ? '/* insert */' : '/* update */'}
`
            let fields = '*' // this.isNew ? '*' : 'category,name,value,config'
            let names = []

            if (!this.selectedCom.length) {
                this.$Message.warning('请先选择左侧菜单！')
                return
            }
            this.sqlText = ''
            this.loading = true
            this.selectedCom.forEach(item => {
                !item.children && names.push(`'${item.name}'`)
            })

            sqlText += `select ${fields} from component where name in (${names.join(',')});`
            this.sqlText = sqlText
            this.loading = false
            this.$copyText(this.sqlText).then(e => {
                this.$Message.success('"SQL语句"已复制到粘贴板，请登录生产环境，打开数据库客户端来执行SQL！')
            })
        },
        startModel() {
            let sqlText = `${this.isNew ? '/* insert */' : '/* update */'}
`
            this.loading = true
            let len = 0
            
            Object.keys(this.selectedModel).forEach(key => {
                let item = this.selectedModel[key]

                if (item.length) {
                    let fields = '*' // this.isNew ? '*' : 'className,comments,properties'
                    let tableName = key + '_model'

                    if (key === 'staticLogic') {
                        tableName = 'static_logic_instance'
                    }
                    if (['twins'].includes(key)) {
                        tableName = key +'_instance'
                    }

                    // containerModel.includes(key) && (fields += ',hierProperties')
                    len += item.length
                    sqlText += `  
select ${fields} from ${tableName} where className in ('${item.join("','")}');
`
                }
            })
            if (!len) {
                this.$Message.warning('请先在左侧选择模型！')
                this.loading = false
                return
            }
            this.sqlText = sqlText
            this.loading = false
            this.$copyText(this.sqlText).then(e => {
                this.$Message.success('"SQL语句"已复制到粘贴板，请登录生产环境，打开数据库客户端来执行SQL！')
            }, err => {
                console.log("file: index.vue:157  err:", err)
            })
        },
        onComSearch() {
            this.comList = this.query ? this.handleQueryNode(this.comListAll, this.query, []) : this.tools.lodash.cloneDeep(this.comListAll)
        },
        handleQueryNode(comList, query, queryList) {
            comList.forEach((menu) => {
                let newMenu = {};
                for (let i in menu) {
                    if (i !== "children") newMenu[i] = this.tools.lodash.cloneDeep(menu[i]);
                }
                if (newMenu.title.indexOf(query) > -1) queryList.push(newMenu);
                if (menu.children && menu.children.length) newMenu.children = [];
                menu.children && this.handleQueryNode(menu.children, query, queryList);
            });
            return queryList;
        },
        ...mapActions('compDesign/config',[
          'loadAllModules',//加载所有页面配置
          ]
        )
    },
    watch: {
        modulesTree: {
            handler(val) {
                let res = []
                val.forEach((item, index) => {
                    res.push({
                        ...item,
                        disabled: true,
                        id: index +1,
                        expand: false,
                    })
                })
                this.comListAll = res;
                this.comList = res;
            }, immediate: true
        },
        list: {
            handler(val) {
                Object.keys(val).forEach((key, index) => {
                    let item = val[key]
                    let model = key.replace('Models', '')
                    let newItem = []

                    model && item.forEach((citem, cindex) => {
                        newItem.push({
                            label: citem.comments || citem.className,
                            model: modelObj[model],
                            value: citem.className
                        })
                    })
                    this.modelListAll[model] = newItem
                })
            }, immediate: true
        }
    },
	computed: {
		...mapState('compDesign/config', [
			'modulesTree', //所有组件配置, tree结构
        ]),
        ...mapState('admin/model', [
          'list'
        ]),
    }
}
</script>

<style lang="less">
@leftWidth: 300px;
.p-makeCompoentSQL {
    position: relative;
    padding: 16px 16px 16px @leftWidth+16px;
    // margin: 16px;
    height: 100%;
    background-color: #fff;
    &-menu {
        position: absolute;
        width: @leftWidth;
        border-right: 1px solid #eee;
        left: 16px;
        top: 0;
        bottom: 0;
        display: flex;
        flex-direction: column;
    }
    .ivu-tree {
        flex: 1;
        overflow: auto;
    }
    .ivu-tabs {
        overflow: auto;
    }
    &-content {
        height: 100%;
        padding-left: 16px;
        overflow: auto;
        .lable {
            padding: 12px 0;
            color: #999;
        }
        .selected {
            padding: 0 12px;
            margin: 16px 0;
            flex-wrap: wrap;
            li {
                margin: 0 16px;
                line-height: 30px;
                // list-style: none;
            }
        }
    }
}
</style>